/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.Workspace;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import managedbean.LoginAdmin.LoginManagerBean;
import merlion.common.entity.Message;
import merlion.common.entity.Staff;
import merlion.common.entity.SystemUserAccount;
import merlion.common.session.stateless.InternalMessageSessionLocal;
import merlion.common.util.Consts;

/**
 *
 * @author Zhang Ying
 */
@ManagedBean
@ViewScoped
public class MsgManagerBean {

    @EJB
    private InternalMessageSessionLocal messageManager;
    @ManagedProperty(value = "#{workspaceManagerBean}")
    private WorkspaceManagerBean workspaceManagerBean;
    // for creation of new message
    private Message newMessage;
    private Collection<SystemUserAccount> allUsers;
    private SystemUserAccount[] selectedReceivers;
    // for viewMsgsSent and Reved
    private Message selectedMessage;
    private Message[] selectedDeletion;
    // for viewSent only
    private Collection<Message> allMySentMessages;
    // for viewRcved only
    private Collection<Message> allMyReceivedMessages;
    private Message repliedOriginalMsg;
    private Message repliedMsg;

    /** Creates a new instance of MsgManagerBean */
    public MsgManagerBean() {
        newMessage = new Message();
    }

    // for creation of new new message and sending
    public String sendNewMessage() {
        if (selectedReceivers.length == 0) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "You should at least choose one receiver.", "You should at least choose one receiver."));
            return null;
        }
        updateCurrentStaff();
        // pass the value from input fields to newMessage
        // 1. sender
        SystemUserAccount sender = workspaceManagerBean.getCurrentStaff().getSystemUserAccount();
        newMessage.setSenderAccId(sender.getId());
        // 2. receivers
        for (SystemUserAccount sua : selectedReceivers) {
            if (!newMessage.getReceiverAccIds().contains(sua.getId())) {
                newMessage.getReceiverAccIds().add(sua.getId());
            }
        }
        // 3. createdTime
        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();
        Timestamp currentTime = new Timestamp(date.getTime());
        newMessage.setCreatedTime(currentTime);
        // 4. haveRead, type
        newMessage.setHaveRead(Consts.MSG_HAVE_READ);
        newMessage.setType(Consts.MSG_TYPE_SENT);
        // send
        if (messageManager.sendMessage(newMessage, sender, selectedReceivers)) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO, "Sending Successful.", "Sending Successful."));
        } else {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "sending Failed", "sending Failed"));
            return null;
        }
        return redirectToViewMsgsSent();
    }

    public Message getNewMessage() {
        return newMessage;
    }

    public void setNewMessage(Message newMessage) {
        this.newMessage = newMessage;
    }

    public Collection<SystemUserAccount> getAllUsers() {
        allUsers = messageManager.getAllSystemUserAccounts();
        return allUsers;
    }

    public void setAllUsers(Collection<SystemUserAccount> allUsers) {
        this.allUsers = allUsers;
    }

    public SystemUserAccount[] getSelectedReceivers() {
        return selectedReceivers;
    }

    public void setSelectedReceivers(SystemUserAccount[] selectedReceivers) {
        this.selectedReceivers = selectedReceivers;
    }

    // for manage all messages sent
    public String viewOneSentMsg(Long id) {
        return redirectToViewMsgSentOne() + "&msgId=" + id;
    }

    public String selectMessage(Long id) {
        setSelectedMessage(messageManager.getMessage(id));
        return null;
    }

    public String deleteOneMsg() {
        if (selectedMessage == null) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Deletion Failed(no selected msg)", "Deletion Failed"));
            return null;
        }
        if (messageManager.deleteMessage(selectedMessage.getId(), workspaceManagerBean.getCurrentStaff().getId())) {
            updateCurrentStaff();
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO, "Deletion Successful.", "Deletion Successful."));
            return null;
        } else {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Deletion Failed", "Deletion Failed"));
            return null;
        }
    }

    public String deleteManyMsgs() {
        if (selectedDeletion.length == 0) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "You should at least choose one message to delete.", "You should at least choose one message to delete."));
            return null;
        }
        if (messageManager.deleteManyMessages(selectedDeletion, workspaceManagerBean.getCurrentStaff().getId())) {
            updateCurrentStaff();
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO, "Deletion Successful.", "Deletion Successful."));
            return null;
        } else {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Deletion Failed", "Deletion Failed"));
            return null;
        }
    }

    public Collection<Message> getAllMySentMessages() {
        allMySentMessages = messageManager.getAllMySentMessage(workspaceManagerBean.getCurrentStaff().getId());
        return allMySentMessages;
    }

    public void setAllMySentMessages(Collection<Message> allMySentMessages) {
        this.allMySentMessages = allMySentMessages;
    }

    public Message[] getSelectedDeletion() {
        return selectedDeletion;
    }

    public void setSelectedDeletion(Message[] selectedDeletion) {
        this.selectedDeletion = selectedDeletion;
    }

    public Message getSelectedMessage() {
        if (selectedMessage == null) {
            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            String parameter = request.getParameter("msgId");
            if (parameter != null) {
                Long id = Long.valueOf(parameter);
                selectedMessage = messageManager.getMessage(id);
            }
        }
        return selectedMessage;
    }

    public void setSelectedMessage(Message selectedMessage) {
        this.selectedMessage = selectedMessage;
    }

    public String getSenderFullName(Long id) {
        return messageManager.getSenderStaff(id).getFullName();
    }

    // for manage sent one view
    public String deleteCurrentOne() {
        if (messageManager.deleteMessage(selectedMessage.getId(), workspaceManagerBean.getCurrentStaff().getId())) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO, "Deletion Successful.", "Deletion Successful."));
            updateCurrentStaff();
        } else {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Deletion Failed", "Deletion Failed"));
            return null;
        }
        return redirectToViewMsgsSent();
    }

    //for manage all messages received
    public String replyMessage() {
        updateCurrentStaff();
        // pass the value from input fields to newMessage
        // 3. createdTime
        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();
        Timestamp currentTime = new Timestamp(date.getTime());
        repliedMsg.setCreatedTime(currentTime);
        // 4. haveRead, type
        repliedMsg.setHaveRead(Consts.MSG_HAVE_READ);
        repliedMsg.setType(Consts.MSG_TYPE_SENT);
        // send
        if (messageManager.replyMessage(repliedMsg)) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO, "Replied Successfully.", "Replied Successfully."));
        } else {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Replied Failed", "Replied Failed"));
            return null;
        }
        return redirectToViewMsgsRcved();
    }

    public String deleteCurrentRcvedOne() {
        if (messageManager.deleteMessage(repliedOriginalMsg.getId(), workspaceManagerBean.getCurrentStaff().getId())) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO, "Deletion Successful.", "Deletion Successful."));
            updateCurrentStaff();
        } else {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Deletion Failed", "Deletion Failed"));
            return null;
        }
        return redirectToViewMsgsRcved();
    }

    public String replyThisMsg(Long id) {
        return redirectToReplyRcvedMsg() + "&msgId=" + id + "&all=false";
    }

    public String replyThisMsgToAll(Long id) {
        return redirectToReplyRcvedMsg() + "&msgId=" + id + "&all=true";
    }

    public Message getRepliedOriginalMsg() {
        if (repliedOriginalMsg == null) {
            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            String parameter = request.getParameter("msgId");
            if (parameter != null) {
                Long id = Long.valueOf(parameter);
                // update as read msg
                repliedOriginalMsg = messageManager.updateNGetReadMsg(id);
            }
        }
        return repliedOriginalMsg;
    }

    public Message getRepliedMsg() {
        if (repliedMsg == null) {
            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            String parameter = request.getParameter("msgId");
            String isForAll = request.getParameter("all");
            if (parameter != null && isForAll != null) {
                Long id = Long.valueOf(parameter);
                repliedOriginalMsg = messageManager.getMessage(id);
                repliedMsg = new Message();
                // set attributes for the new repliedMsg
                repliedMsg.setSubject("RE: " + repliedOriginalMsg.getSubject());
                repliedMsg.setContent("-------------------------------------------------\n\n"
                        + repliedOriginalMsg.getContent());
                repliedMsg.setSenderAccId(workspaceManagerBean.getCurrentStaff().getSystemUserAccount().getId());
                if (isForAll.equals("true")) {
                    Collection<Long> receiverAccIds = new ArrayList<Long>();
                    Long originalSenderId = repliedOriginalMsg.getSenderAccId();
                    receiverAccIds.add(originalSenderId);
                    for (Long rcvId : repliedOriginalMsg.getReceiverAccIds()) {
                        if (!originalSenderId.equals(rcvId)) {
                            receiverAccIds.add(rcvId);
                        }
                    }
                    repliedMsg.setReceiverAccIds(receiverAccIds);
                } else {
                    Collection<Long> receiverAccIds = new ArrayList<Long>();
                    receiverAccIds.add(repliedOriginalMsg.getSenderAccId());
                    repliedMsg.setReceiverAccIds(receiverAccIds);
                }
            }
        }
        return repliedMsg;
    }

    public void setRepliedMsg(Message repliedMsg) {
        this.repliedMsg = repliedMsg;
    }

    public void setRepliedOriginalMsg(Message repliedOriginalMsg) {
        this.repliedOriginalMsg = repliedOriginalMsg;
    }

    public String viewOneRcvedMsg(Long id) {
        return redirectToViewMsgRcvedOne() + "&msgId=" + id;
    }

    public Collection<Message> getAllMyReceivedMessages() {
        allMyReceivedMessages = messageManager.getAllMyReceivedMessages(workspaceManagerBean.getCurrentStaff().getId());
        return allMyReceivedMessages;
    }

    public void setAllMyReceivedMessages(Collection<Message> allMyReceivedMessages) {
        this.allMyReceivedMessages = allMyReceivedMessages;
    }

    public String getSelectedMsgStaffName(Long id) {
        return messageManager.getSenderStaff(id).getFullName();
    }

    // for general purpose
    public WorkspaceManagerBean getWorkspaceManagerBean() {
        return workspaceManagerBean;
    }

    public void setWorkspaceManagerBean(WorkspaceManagerBean workspaceManagerBean) {
        this.workspaceManagerBean = workspaceManagerBean;
    }

    private void updateCurrentStaff() {
        Staff s = messageManager.getUpdatedStaff(workspaceManagerBean.getCurrentStaff().getId());
        workspaceManagerBean.setCurrentStaff(s);
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(LoginManagerBean.AUTH_KEY, s);
    }

    // for redirecting
    private String getRedirectPath(String path) {
        return path + "?faces-redirect=true";
    }

    public String redirectToViewMsgsSent() {
        return getRedirectPath(Consts.VIEW_MSGS_SENT);
    }

    public String redirectToViewMsgsRcved() {
        return getRedirectPath(Consts.VIEW_MSGS_RCVED);
    }

    public String redirectToViewMsgSentOne() {
        return getRedirectPath(Consts.VIEW_MSGS_SENT_ONE);
    }

    public String redirectToViewMsgRcvedOne() {
        return getRedirectPath(Consts.VIEW_MSGS_RCVED_ONE);
    }

    public String redirectToCreateNewMsg() {
        return getRedirectPath(Consts.SEND_NEW_MSG);
    }

    public String redirectToReplyRcvedMsg() {
        return getRedirectPath(Consts.REPLY_RCVED_MSG);
    }
    
    // for home page
    
    public Collection<Message> getNewRcvedUnread(Long accId){
        return messageManager.getNewRcvedUnreadMsg(accId);
    }
}
